package cn.sciento.farm.devicemanager.service.impl;

import cn.sciento.farm.devicemanager.common.constant.AlarmConstant;
import cn.sciento.farm.devicemanager.dao.entity.DevAlarmPersonRel;
import cn.sciento.farm.devicemanager.dao.mapper.DevAlarmMapper;
import cn.sciento.farm.devicemanager.dao.mapper.DevAlarmPersonRelMapper;
import cn.sciento.farm.devicemanager.dao.model.AlarmForm;
import cn.sciento.farm.devicemanager.service.AlarmService;
import cn.sciento.farm.devicemanager.service.CollectionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class AlarmServiceImpl implements AlarmService {

    @Autowired
    private DevAlarmMapper devAlarmMapper;

    @Autowired
    private DevAlarmPersonRelMapper devAlarmPersonRelMapper;

    @Autowired
    private CollectionService collectionService;

    @Transactional()
    @Override
    public int create(AlarmForm alarmForm) {
        if(StringUtils.isEmpty(alarmForm.getStrategy() )){
            alarmForm.setStrategy(AlarmConstant.SEND_STRATEGY_TIME);
        }
        int count =  devAlarmMapper.insert(alarmForm);
        createAlarmPersonRel(alarmForm);
        return count;
    }


    public int deleteAlarmPersonRel(Long alarmId){
        QueryWrapper queryWrapper = new QueryWrapper<DevAlarmPersonRel>();
        queryWrapper.eq("alarm_id",alarmId);
        return devAlarmPersonRelMapper.delete(queryWrapper);
    }

    public int createAlarmPersonRel(AlarmForm alarmForm){
        if(null == alarmForm.getId()){
            return 0;
        }
        AtomicInteger count = new AtomicInteger();
        alarmForm.getPersonIds().stream().forEach(personId->{
            DevAlarmPersonRel rel = new DevAlarmPersonRel();
            rel.setAlarmId(alarmForm.getId());
            rel.setPersonId(personId);
            count.addAndGet(devAlarmPersonRelMapper.insert(rel));
        });
        return count.get();
    }

    @Transactional()
    @Override
    public int updateById(AlarmForm alarmForm) {
        deleteAlarmPersonRel(alarmForm.getId());
        int count =  devAlarmMapper.updateById(alarmForm);
        createAlarmPersonRel(alarmForm);
        return count;
    }

    @Override
    public int deleteById(Long id) {
        return devAlarmMapper.deleteById(id);
    }

    @Override
    public List<AlarmForm> getByAreaId(int areaId) {
        return devAlarmMapper.getByAreaId(areaId);
    }

    @Override
    public AlarmForm getById(Long id) {
        return devAlarmMapper.getById(id);
    }

    @Override
    public List<AlarmForm> getByCollectionId(Long id) {
        return devAlarmMapper.getByCollectionId(id);
    }
}
